import sensor, lcd
import utime
from fpioa_manager import fm
from Maix import GPIO
from machine import UART
from board import board_info
from machine import Timer

# RGB 相关变量
rgb_drv = []
rgb_g_v = 0

# 串口相关变量初始化
uart_A = None

# 环境光强度
env_light_ratio = 0

# sensor 相关变量
sensor_capture_cycle = 50
sensor_capture_cnt = 50


# 串口数据格式为ASCII：长度+对象+数据

# 定时器0channel0处理串口发送
def timer0_channel0_handler(a):
    global uart_A
    uart_wr_len = uart_A.write(chr(2)+'L'+chr(env_light_ratio)+'\r\n')

# 定时器1channel0用于驱动led
def timer1_channel0_handler(a):
    global rgb_drv
    global rgb_g_v
    # 绿色led周期闪烁，表示系统正常
    rgb_g_v ^= 1
    rgb_drv[1].value(rgb_g_v)

def board_init():
    lcd.init(freq=15000000)
    lcd.draw_string(100, 100, "Smart Desk Lamp", lcd.RED, lcd.BLACK)
    lcd.draw_string(200, 200, "--hehung", lcd.RED, lcd.BLACK)
    # 相机初始化
    sensor.reset()
    sensor.set_pixformat(sensor.RGB565)
    sensor.set_framesize(sensor.QVGA)
    # 垂直反转相机
    sensor.set_vflip(1)
    # 设置相机亮度为0
    sensor.set_brightness(0)
    # 开始撞去图像
    sensor.run(1)
    # 跳过不稳定帧
    sensor.skip_frames()


    # RGB 初始化
    io_led_green = 12
    io_led_red = 13
    io_led_blue = 14
    fm.register(io_led_green, fm.fpioa.GPIO0)
    fm.register(io_led_red, fm.fpioa.GPIO1)
    fm.register(io_led_blue, fm.fpioa.GPIO2)
    led_g=GPIO(GPIO.GPIO0, GPIO.OUT)
    led_r=GPIO(GPIO.GPIO1, GPIO.OUT)
    led_b=GPIO(GPIO.GPIO2, GPIO.OUT)
    global rgb_drv
    rgb_drv = [led_r, led_g, led_b]
    # 关闭三色灯
    for i in range(3):
        rgb_drv[i].value(1)

    # 串口初始化
    # 初始化串口，PIN10为TX，PIN9为RX
    fm.register(board_info.PIN10, fm.fpioa.UART1_TX, force=True)
    fm.register(board_info.PIN9, fm.fpioa.UART1_RX, force=True)
    # 设置串口参数，波特率为115200
    global uart_A
    uart_A = UART(UART.UART1, 115200, 8, 0, 0, timeout=1000, read_buf_len=4096)

    # 定时器初始化
    tim0ch0 = Timer(Timer.TIMER0, 
            Timer.CHANNEL0, 
            mode=Timer.MODE_PERIODIC, 
            period=1000, 
            unit=Timer.UNIT_MS, 
            callback=timer0_channel0_handler, 
            start=False, 
            arg = 0,
            priority=7, 
            div=0)
    tim1ch0 = Timer(Timer.TIMER1, 
            Timer.CHANNEL0, 
            mode=Timer.MODE_PERIODIC, 
            period=1000, 
            unit=Timer.UNIT_MS, 
            callback=timer1_channel0_handler, 
            arg=0, 
            start=False, 
            priority=7, 
            div=0)
    # utime.sleep_ms(50)
    tim0ch0.start()
    tim1ch0.start()


if __name__ == "__main__":
    board_init()

    while (True):
        if sensor_capture_cycle == sensor_capture_cnt:
            sensor_capture_cnt = 0
            # 图片采集并通过lcd显示出来，分析光照强度
            img = sensor.snapshot()
            lcd.display(img)
            # 获取lab统计结果
            lab_color = img.get_statistics()
            # 获取图片亮度平均值，作为光照亮度
            env_light_ratio = lab_color[0]
            print ("光照强度为："+str(env_light_ratio))

        # 串口接受处理
        read_data = uart_A.read()
        if read_data:
            read_str = read_data.decode('utf-8')
            print("received data:",read_str)

        sensor_capture_cnt = sensor_capture_cnt + 1
        utime.sleep_ms(20)
    
